<template>
  <div class="tabbar">
    <ul>
      <li
        v-for="(item, index) in routerList"
        :key="index"
        @click="switchTab(item.path)"
      >
        <img
          :src="$route.path.includes(item.path) ? item.selected : item.active"
          alt=""
        />
        <span :class="$route.path.includes(item.path) ? 'active' : ''">{{
          item.title
        }}</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Tabbar",
  data() {
    return {
      routerList: [
        {
          title: "首页",
          path: "/",
          active: "../images/list.png",
          selected: "../images/home-select.png",
        },
        {
          title: "分类",
          path: "/list",
          active: "../images/list.png",
          selected: "../images/list-select.png",
        },
        {
          title: "购物车",
          path: "/cart",
          active: "../images/cart.png",
          selected: "../images/cart-select.png",
        },
        {
          title: "我的",
          path: "/my",
          active: "../images/my.png",
          selected: "../images/my-select.png",
        },
      ],
    };
  },
  methods: {
    switchTab(path) {
      const token = window.sessionStorage.getItem("token");
      // console.log(token);
      if (token == null && path == "/cart") {
        //如果token为空，则跳转到登录页面
        this.$router.push("/login");
        return;
      }
      //判断是否是同一个路由
      if (this.$route.path === path) return;
      //跳转到对应页面
      if (path == "/cart") {
        this.$router.push("/cart/" + token);
        return;
      }
      this.$router.replace(path);
    },
  },
};
</script>

<style scoped>
.tabbar {
  position: fixed;
  z-index: 999;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: pink;
}
.tabbar ul {
  display: flex;
  justify-content: space-around;
  height: 100%;
  align-items: center;
  justify-items: center;
}
.tabbar ul li {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-items: center;
  font-size: 15px;
}
.tabbar ul li img {
  width: 31px;
  height: 31px;
}
.active {
  color: red;
}
</style>